﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;


using WeifenLuo.WinFormsUI.Docking;
using eBook.Core.BusinessObjects;
using System.Reflection;
using eBook.Core.Contracts;
using System.IO;
using System.Diagnostics;

namespace eBook.WinApp
{
  public partial class frmBookDetail : DockContent
  {
    private ILibRepository _libRepository;
    private string _reviewTemplate;
    private boBook _book;

    public frmBookDetail()
    {
      InitializeComponent();
      _reviewTemplate = "<html><head><style>body{{ font-family:{0}; font-size:{1}pt;}}</style></head><body>{2}<br/><br/>{3}</body></html>";
    }

    public frmBookDetail(ILibRepository libRepository) : this()
    {
      Application.DoEvents();
      _libRepository = libRepository;
    }


    public void RenderBookDetail(int bookId)
    {
      if ( bookId <= 0 )
        throw new ArgumentException("bookId");
      
      Application.DoEvents();

      _book = _libRepository.GetBookById(bookId);
      
      BindDetailControls(_book);

      string fontName = pnlDetail.Font.FontFamily.Name;
      string fontSize = pnlDetail.Font.SizeInPoints.ToString().Replace(',', '.');
      BindReviewHtml(_book, fontName, fontSize);    

      if (!string.IsNullOrEmpty(_book.MediumImageURL))
        picSmall.LoadAsync(_book.MediumImageURL);
      else
        picSmall.Image = null;

      string isbn = _book.ISBN10;
      if ( string.IsNullOrEmpty(isbn) )
        isbn = _book.ISBN13;

      string formCaption= _book.Title;
      if (formCaption.Length > 20)
        formCaption = formCaption.Substring(0, 20) + " ...";

      this.Text = string.Format("[{0}] {1}", isbn, formCaption);    
    }

    private void BindReviewHtml(boBook book, string fontName, string fontSize)
    {
      string bookLinks = string.Empty;
      if ( book.Links != null && book.Links.Count() > 0 )
      {
        var t = ( from x in book.Links
                  select string.Format("<a href=\"{0}\">{1}</a>", x.Path, x.Name) ).ToArray();
        bookLinks = string.Join("<br/>", t);
      }

      string review = string.Format(_reviewTemplate
                                   , fontName, fontSize, bookLinks, book.EditorialReview);
      wbReview.DocumentText = review;
    }

    private void BindDetailControls(boBook book)
    {
      lblBigTitle.Text = book.Title;
      lblBigSubtitle.Text = book.Subtitle;

      string fullPath = Path.Combine(Configuration.BasePath, book.RelativePath);
      txtFullPath.Text = fullPath;
      lblMissing.Visible = !File.Exists(fullPath);
      btnOpen.Enabled = !lblMissing.Visible;

      txtTopics_.Lines = book.Topics.Select(x => x.Name).ToArray();
      txtCategories_.Lines = book.Categories.Select(x => x.Name).ToArray();

      txtBookID.DataBindTo(book, "BookID");
      txtDateCreated.DataBindTo(book, "DateCreated");
      txtDateModified.DataBindTo(book, "DateModified");
      txtDeweyDecimal.DataBindTo(book, "DeweyDecimal");
      txtEdition.DataBindTo(book, "Edition");      
      txtISBN10.DataBindTo(book, "ISBN10");
      txtISBN13.DataBindTo(book, "ISBN13");
      txtLCCN.DataBindTo(book, "LCCN");
      txtNumberOfPages.DataBindTo(book, "NumberOfPages");
      txtPublisherName.DataBindTo(book, "PublisherName");
      txtPublicationDate.DataBindTo(book, "PublicationDate");
      txtAuthorsAsText.DataBindTo(book, "AuthorsAsText");
    }

    private void picSmall_Click(object sender, EventArgs e)
    {
      if (_book == null)
        throw new Exception("_book is not defined");

      if (string.IsNullOrEmpty(_book.LargeImageURL))
        return;

      Panel pnlPreview = new Panel { Parent = pnlDetail, Dock = DockStyle.Fill };

      Button btnClose = new Button { Text = "Close", Parent = pnlPreview };
      btnClose.Click += delegate { pnlDetail.Controls.Remove(pnlPreview); };      

      PictureBox picPreview = new PictureBox { Parent = pnlPreview, BackColor = Color.Transparent, Dock = DockStyle.Fill, SizeMode = PictureBoxSizeMode.CenterImage };
      picPreview.LoadAsync(_book.LargeImageURL);     

      pnlPreview.BringToFront();
    }

    private void wbReview_Navigating(object sender, WebBrowserNavigatingEventArgs e)
    {
      e.Cancel = _book.Links.FirstOrDefault(x => x.Path == e.Url.AbsoluteUri) != null;
      if (e.Cancel)
        System.Diagnostics.Process.Start(e.Url.AbsoluteUri);
    }

    private void btnRefresh_Click(object sender, EventArgs e)
    {      
      try
      {
        Cursor.Current = Cursors.WaitCursor;
        this.RenderBookDetail(_book.BookID);
      }
      finally
      {
        Cursor.Current = Cursors.Default;
      }
    }

    private void btnOpen_Click(object sender, EventArgs e)
    {
      string fullPath = Path.Combine(Configuration.BasePath, _book.RelativePath);

      var readerProcess = new Process();
      ProcessStartInfo si = new ProcessStartInfo(fullPath);
      si.CreateNoWindow = false;
      readerProcess.StartInfo = si;
      readerProcess.Start();
    }

  }
}
